import os
import httpx
import json
import logging
from typing import Dict, Optional, List, Any
import time

logger = logging.getLogger(__name__)

# 简单的内存缓存
_character_cache = {}
_cache_expiry = {}
CACHE_DURATION = 300  # 5分钟缓存

async def load_character_profile(chat_id: int = None, language: str = None) -> Optional[Dict]:
    """从API加载角色配置"""
    if chat_id is None:
        return None
    
    # 检查缓存
    cache_key = f"{chat_id}_{language}"
    current_time = time.time()
    
    if (cache_key in _character_cache and 
        cache_key in _cache_expiry and 
        current_time < _cache_expiry[cache_key]):
        return _character_cache[cache_key]
        
    try:
        # 从环境变量获取API地址
        api_url = os.getenv("CHARACTER_PROFILE_API", "http://127.0.0.1:3000/api/ai-persons/getCharacterProfile")
        
        # 方法1: 使用查询参数 (Query Parameter)
        async with httpx.AsyncClient(timeout=10.0) as client:
            response = await client.get(f"{api_url}?id={chat_id}&language={language}")
            
            if response.status_code != 200:
                logger.error(f"API request failed with status code: {response.status_code}")
                return None
            
            response_data = response.json()
                
            if not response_data.get("success"):
                logger.error(f"API请求返回success=false: {response_data}")
                return None
                
            profile = response_data.get("data")
            
            if profile:
                # 新数据结构处理: voice_settings直接在data层级，不需要特殊处理
                # 新结构中包含: promptWord, aiPersion_id, voice_settings, persionImageDescription
                # voice_settings包含: vol, pitch, speed, voice_id, timber_weights
                
                # 确保voice_settings字段存在且格式正确
                if "voice_settings" not in profile:
                    logger.warning(f"角色配置中缺少voice_settings字段: {profile}")
                
                # 缓存角色配置
                _character_cache[cache_key] = profile
                _cache_expiry[cache_key] = current_time + CACHE_DURATION
                

                return profile
                
            logger.warning(f"未找到角色ID: {chat_id}的配置")
            return None
    except Exception as e:
        logger.error(f"从API加载角色配置出错: {str(e)}", exc_info=True)
        return None 